package com.thread.test1;

/**
 * @description: TODO 类描述
 * @author: YUANG
 * @date: 2022/3/6
 **/
public class MyThreadTest {
    public static void main(String[] args) throws InterruptedException {
//        test1();
//        joinTest();
        MyThread t = new MyThread();
        t.start();
        Thread.sleep(1000);
        /**
         * 1 中断 t
         *  t 此时在 h.join(); ,此方法会立刻抛出InterruptedException
         *  被catch 打印
         *  h.interrupt(); 立刻中断h线程
         *  t线程结束
         *  main线程join t t线程结束
         *  main也结束
         *  JVM停止
         *
         */
        t.interrupt();
        t.join();
        System.out.println("end");
    }

    public static class MyThread extends Thread {
        @Override
        public void run() {
            HelloThread h = new HelloThread();
            h.start();
            try {
                h.join();
            } catch (InterruptedException e) {
                System.out.println("interrupted!");
            }
            h.interrupt();
        }
    }

    public static class HelloThread extends Thread {
        @Override
        public void run() {
            int n = 0;
            while (true) {
                System.out.println(isInterrupted());
                n++;
                System.out.println(n + " hello!");
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    break;
                }
            }
        }
    }


    private static void joinTest() throws InterruptedException {
        System.out.println("start");
        Thread t = new Thread(() -> {
            System.out.println("hello");

        });
        t.start();
        //main 线程会等待t结束后再执行
        t.join();
        //main 等待t超过1000ms后如果未响应则跳过等待直接执行
//        t.join(1000L);
        System.out.println("end");
    }

    private static void test1() {
        System.out.println("main run");
        Thread t = new Thread(() -> {
            System.out.println("thread run");
            try {
                Thread.sleep(1000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("thread end");
        });
        t.start();

        System.out.println("main end");
    }
}
